package com.tbit.uqbike.center.config.ThreadPoolConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * center 中同步设备上报终态信息的MQ消费者线程池
 * @author Zhang Zhi Liang
 * @date 2024/4/22 10:31
 */
@RefreshScope
@Configuration
public class MsgThreadPoolConfig {

    @Value("${mqThreadPool.corePoolSize:16}")
    private Integer corePoolSize;
    @Value("${mqThreadPool.maxPoolSize:20}")
    private Integer maxPoolSize;
    @Value("${mqThreadPool.keepAliveSeconds:60}")
    private Integer keepAliveSeconds;
    @Value("${mqThreadPool.queueCapacity:5000}")
    private Integer queueCapacity;
    @Value("${mqThreadPool.namePrefix:center-consumer-thread}")
    private String namePrefix;


    @Autowired
    private MsgRejectedExecutionHandler rejectedExecutionHandler;

    @Bean("msgThreadPoolExecutor")
    public ThreadPoolExecutor msgThreadPoolExecutor(){
        ThreadFactory threadFactory = new ThreadFactory() {
            final AtomicInteger index = new AtomicInteger(0);
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName(String.format("%s-%d",namePrefix,index.getAndIncrement()));
                return thread;
            }
        };
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), threadFactory, rejectedExecutionHandler );
    }

}
